﻿using System;
using System.IO;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting.Display;


namespace YGBookmark.Utils
{
    /// <summary>
    /// 基于Serilog 4.2.0的日志记录封装类
    /// </summary>
    public static class Logger
    {
        private static ILogger _logger;
        private const string OutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}";

        /// <summary>
        /// 静态构造函数初始化日志配置
        /// </summary>
        static Logger()
        {
            ConfigureGlobalLogger();
        }

        /// <summary>
        /// 配置全局日志记录器（兼容Serilog 4.x API）
        /// </summary>
        private static void ConfigureGlobalLogger()
        {
            try
            {
                var logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs", "log-.txt");

                var configuration = new LoggerConfiguration()
                    .MinimumLevel.Debug()
                    .Enrich.FromLogContext();

                // 文件日志配置（兼容新版API）
                configuration.WriteTo.File(
                    path: logPath,
                    rollingInterval: RollingInterval.Day,
                    retainedFileCountLimit: 7,
                    fileSizeLimitBytes: 10 * 1024 * 1024,
                    rollOnFileSizeLimit: true,
                    outputTemplate: OutputTemplate,
                    shared: true
                );

                _logger = configuration.CreateLogger();
                LogInformation("Logger initialized successfully");
            }
            catch (Exception ex)
            {
                // 极简后备配置
                _logger = new LoggerConfiguration()
                     //.WriteTo.Sink(outputTemplate: "[Emergency] {Message}")
                    .MinimumLevel.Error()
                    .Enrich.FromLogContext()
                    .CreateLogger();

                LogError($"Logger init failed: {ex}");
            }
        }

        /// <summary>
        /// 记录调试信息
        /// </summary>
        public static void LogDebug(string message)
        {
            _logger.Debug(message);
        }

        /// <summary>
        /// 记录常规信息
        /// </summary>
        public static void LogInformation(string message)
        {
            _logger.Information(message);
        }

        /// <summary>
        /// 记录警告信息
        /// </summary>
        public static void LogWarning(string message, Exception ex = null)
        {
            _logger.Warning(ex, message);
        }

        /// <summary>
        /// 记录错误信息
        /// </summary>
        public static void LogError(string message, Exception ex = null)
        {
            _logger.Error(ex, message);
        }

        /// <summary>
        /// 记录致命错误
        /// </summary>
        public static void LogFatal(string message, Exception ex = null)
        {
            _logger.Fatal(ex, message);
        }

        /// <summary>
        /// 安全关闭日志系统
        /// </summary>
        public static void CloseAndFlush()
        {
            try
            {
                if (_logger is IDisposable disposable)
                {
                    disposable.Dispose();
                    LogInformation("Logger disposed successfully");
                }
            }
            catch (Exception ex)
            {
                LogError($"Logger disposal failed: {ex}");
            }
        }
    }
}